﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ManagedWinapi;
using ManagedWinapi.Windows;

namespace wutils
{
    class MinimizedWindowBigButton : Button
    {
        public MinimizedWindowBigButton(SystemWindow window, TaskMan theContainer)
        {
            Window = window;
            TheContainer = theContainer;
            Initialize();
        }

        private SystemWindow Window { get; set; }
        private TaskMan TheContainer { get; set; }
        
        private void Initialize()
        {
            Name = "btn__" + Window.HWnd;
            Text = "";
            Height = 64;
            Width = 64;

            Click += ClickHandler;
            GotFocus+=MinimizedWindowBigButton_GotFocus;

            if (Window.Process.Modules.Count <= 0) return;

            Icon icon = ExtendedFileInfo.GetIconForFilename(Window.Process.Modules[0].FileName, false);
            Image = Image.FromHbitmap(icon.ToBitmap().GetHbitmap());

            WindowUtils.MinimizedWindowsChanged += OnMinimizedWindowsChanged;
        }

        private void MinimizedWindowBigButton_GotFocus(object sender, EventArgs e)
        {
            TheContainer.WindowTitle = Window.Title;
        }

        private void OnMinimizedWindowsChanged(object sender, WindowEventArgs e)
        {
            if (e.Action != EventAction.REMOVED) return;
            if (Window.HWnd != e.Window.HWnd) return;

            Destroy();
        }

        private void ClickHandler(object sender, EventArgs e)
        {
            Restore();
            TheContainer.Hide();
        }

        public void Restore()
        {
            WindowUtils.Restore(Window);
        }

        public void Destroy()
        {
            if (TheContainer == null) return;

            TheContainer.ButtonsContainer.Controls.Remove(this);

            Window = null;
            WindowUtils.MinimizedWindowsChanged -= OnMinimizedWindowsChanged;
            Dispose();
        }
    }
}
